# -*- coding: utf-8 -*-
# coding:utf-8
__author__ = 'lancelrq'

import Oauth2Provider
import wejudge.kernel.general as kernel
import wejudge.apps.account.models as AccountModel
import wejudge.apps.contest.models as ContestModel
import wejudge.kernel.contest as ContestKernel


class Contest(Oauth2Provider.Oauth2Provider, ContestKernel.ContestProvider):

    def __init__(self, request):
        Oauth2Provider.Oauth2Provider.__init__(self, request)

    def judgestatus_timeline(self):
        self._action = kernel.const.VIEW_ACTION_DEFAULT
        if not self._method_check("POST"):
            return

        appid = self._request.GET.get('appid', '')
        appsecert = self._request.POST.get('secret', '')
        contest_id = self._request.POST.get('contest_id', '')
        first_status_id = self._request.POST.get('first_status_id', '')
        limit = self._request.POST.get('limit', '100')
        flag = self._request.POST.get('flag', '-3')

        try:
            flag = int(flag)
        except:
            flag = -3

        if flag not in kernel.const.JUDGE_STATUS_FLAG_DESC.keys():
            flag = -3

        client = self._get_client(appid)
        if client is False:
            return

        if not self._check_app_secret(client, appsecert):
            return

        try:
            limit = int(limit)
        except:
            limit = 100

        try:
            first_status_id = int(first_status_id)
        except:
            first_status_id = -1

        if limit > 200 or limit < 0:
            limit = 100

        contest = self._get_contest(contest_id)
        if contest is None:
            self._context = self._OauthError(40301, "Contest not found.")
            return

        if flag == -3:
            judgestatus = contest.judge_status
        else:
            judgestatus = contest.judge_status.filter(flag=flag)

        if first_status_id != -1:
            judgestatus = judgestatus.filter(id__lt=first_status_id).order_by('-id')[:limit]
        else:
            judgestatus = judgestatus.order_by('-id')[:limit]

        status_list = []

        for status in judgestatus:

            first_status_id = status.id

            status_list.append({
                "id": status.id,
                "problem": status.problem.id,
                "author": status.author.id,
                "flag": status.flag,
                "lang": status.lang,
                "timestamp": status.timestamp,
                "exe_time": status.exe_time,
                "exe_mem": status.exe_mem,
                "code_len": status.code_len
            })

        self._context = self._OauthSuccess({
            "status_list": status_list,
            "limit": limit,
            "first_status_id": first_status_id,
            "count": len(status_list)
        })
